<template>
  <div class="subPage">
    <nav-bar title="消息提醒" position="left" :isChooseStatus="isChooseStatus" color='linear-gradient(90deg, #557DF5 0%, #3F4ADE 100%)' :goBack="goBack" :isMsg='true' fontColor='#fff' ></nav-bar>
    <div class="top clearfix">
      <div class="backgr"></div>
      <div class="init">
        <div
          v-for="(item, index) in navList"
          :key="index"
          class="clearfix item"
          @click="goList(item)"
        >
          <img v-if="imgUrl" :src="imgUrl + item.img" />
          <div>{{ item.name }}</div>
          <div class="unReadPoint" v-if="index===0 && unreadStatic.chat_info*1>0" >{{unreadStatic.chat_info}}</div>
          <div class="unReadPoint" v-if="index===1 && unreadStatic.report_info*1>0" >{{unreadStatic.report_info}}</div>
          <div class="unReadPoint" v-if="index===2 && unreadStatic.notice_info*1>0" >{{unreadStatic.notice_info}}</div>
          <div class="unReadPoint" v-if="index===3 && unreadStatic.system_info*1>0" >{{unreadStatic.system_info}}</div>
        </div>
      </div>
    </div>
    <scroll-view
      scroll-y="true"
      :lower-threshold="50"
       :refresher-triggered="triggered"
      :refresher-enabled="true"
      @refresherrefresh="onPullDownRefresh"
      @scrolltolower="queryMore"
      :class="{ msglist: true, clearfix: true }"
      v-if="showArray.length > 0"
    >
      <div class="hadMsg">
        <span @click="readAll">全部标为已读</span>
      </div>
      <div class="infoAll" v-for="(item, index) in showArray" :key="index">
        <ul>
          <li
            @touchstart="touchStart($event, index)"
            @touchend="touchEnd($event, index)"
            :data-type="item.type"
            @click="recover(index, item)"
          >
            <div class="chooseImg" v-if="isChooseStatus" @click.stop="chooseMsg(index)" >
              <img :src="item.isChoose?'/static/images/checked.png':'/static/images/uncheck.png'" alt="">
            </div>
            <div :class="['imgInfo',{'imgChooseMargin':isChooseStatus}]">
              <img v-if="item.info_type == '0'" :src="imgUrl + 'msg1.png'" />
              <img v-if="item.info_type == '4'" :src="imgUrl + 'msg1.png'" />
              <img v-if="item.info_type == '1'" :src="imgUrl + 'msg2.png'" />
              <img v-if="item.info_type == '2'" :src="imgUrl + 'msg3.png'" />
              <img v-if="item.info_type == '3'" :src="imgUrl + 'msg4.png'" />
            </div>
            <div :class="[{'centerInfo':true},{'chooseWidth':isChooseStatus}]">
              <div class="name clearfix">
                <span class="fl" v-if="item.info_type == '0' || item.info_type == '4'"
                  >问诊消息
                  <span
                    v-if="item.if_read == '0' && item.readNum > 0"
                    class="radiusNum"
                    >{{ item.readNum }}</span
                  ></span
                >
                <span class="fl" v-if="item.info_type == '1'"
                  >报告消息
                  <span v-if="item.if_read == '0'" class="radius"></span
                ></span>
                <span class="fl" v-if="item.info_type == '2'"
                  >公告消息
                  <span v-if="item.if_read == '0'" class="radius"></span
                ></span>
                <span class="fl" v-if="item.info_type == '3'"
                  >系统消息
                  <span v-if="item.if_read == '0'" class="radius"></span
                ></span>
                <span class="fr time" v-if="item.showTime!=='NaN-N'">{{ item.showTime }}</span>
              </div>
              <div class="sonName clearfix">
                <span v-if="item.info_type == '0' || item.info_type == '4'|| item.info_type == '5'">
                  您好,{{item.dept_name+''+item.doctor_identity_desc+''+item.sonName}}已经回复了您的{{item.category_str}},请点击查看详细内容
                </span>
                <span v-else-if="item.info_type == '2'" class="info">{{
                  item.info_title
                }}</span>
                <span v-else-if="item.info_type == '3'" class="info">{{
                  item.info_text
                }}</span>
              </div>
            </div>
            <div class="top" @click.stop="read(index,item)">
              标为已读
            </div>
            <div class="delect" @click.stop="delect(index, item)">
              删除
            </div>
          </li>
        </ul>
      </div>
    </scroll-view>
    <div v-if="showArray.length===0 && !delayShowData" class="msglist clearfix">
      <img :src="noMsgImg" class="noneimg" />
    </div>
    <div v-if="isChooseStatus" :class="['bottomChooseBox',{'ifIphonex':ifIphonex}]" >
      <span class="fl leftCheckBox">
        <img @click="checkAllMsg" :src="allCheck?'/static/images/checked.png':'/static/images/uncheck.png'" alt="">
      </span>
      <span :class="{'redFont':allCheck}" @click="checkAllMsg">{{allCheck?'取消全选':'全选'}}</span>
      <span :class="['deleteBtn', 'fr',{'canDelete':true}]" @click="batchDelete" >删除</span>
    </div>
    <i-toast id="toast" />
  </div>
</template>
<script>
let app = getApp();
let store = app.store;
import api from "@/api/api";
import Bus from "@/utils/bus.js";
import * as types from "@/store/types";
import { mapState } from "vuex";
import nim from "@/utils/nim";
import { $Toast } from '../../../../../static/iview/base'
import navBar from '@/components/navBar'
export default {
  components: {
    navBar
  },
  computed: {
    ...mapState(["talkInfo", "regularInfo", "sessionsList",'ifIphonex']),
  },
  data() {
    return {
      msgList: [],
      imgUrl: "",
      noMsgImg: "",
      msg1Img: "",
      msg2Img: "",
      msg3Img: "",
      msg4Img: "",
      navList: [
        {
          name: "问诊消息",
          img: "msg1.png",
          value: 0,
        },
        {
          name: "报告消息",
          img: "msg2.png",
          value: 1,
        },
        {
          name: "公告消息",
          img: "msg3.png",
          value: 2,
        },
        {
          name: "系统消息",
          img: "msg4.png",
          value: 3,
        },
      ],
      unreadStatic: {},
      type: "", // 1：报告消息 2：公告消息  3：系统消息   0 问诊消息
      ongoingList: [], // 正在预约中的数据
      msgTipsList: [], // 获取消息提醒列表数据
      showArray: [], // 页面上显示的数组
      page: 1,
      showTypeStatus: false,
      type: "",
      startX: "",
      endX: "",
      oldList: [],
      total: 0,
      navHeight: 60,
      navBtnInfo: {
        height: 32,
        top: 24,
        right: 365
      },
      isChooseStatus: false,
      allCheck: false,
      triggered: false,
      beingChooseList: [], // 要删除的消息数组
      delayShowData: true
    };
  },
  onShow() {
    this.triggered = false
    this.allCheck = false
    this.isChooseStatus = false
    this.getNavInfo()
    this.imgUrl = api.imgUrl;
    this.ongoingList = [];
    this.oldList = [];
    store.dispatch({
      type: "CurrentChatTo_Change",
      payload: "",
    });
    setTimeout(() => {
      this.showArray = []
      this.page = 1;
      this.ongoingAppointment();
    }, 300);
  },
  onUnload() {
    this.showArray = []
  },
  mounted() {
    let that = this;
    that.page = 1;
    that.imgUrl = api.imgUrl;
    that.msg1Img = that.imgUrl + "msg1.png";
    that.noMsgImg = that.imgUrl + "noMsg.png";
    that.msg2Img = that.imgUrl + "msg2.png";
    that.msg3Img = that.imgUrl + "msg3.png";
    that.msg4Img = that.imgUrl + "msg4.png";
    console.log(that.msg1Img, "that.msg1Img");
    // this.initBus()
  },
  methods: {
    // 初始化im信息列表
    initBus() {
      Bus.$on("addMsg", (res, id) => {
        let keyTwo = Object.keys(res[id]);
        let allObj = res[id];
        let lastKey = keyTwo[keyTwo.length - 1];
        let nowMsg = allObj[lastKey]; // 发来消息对象
        // 该会话在这里显示的列表
        if (that.oldList.length > 0) {
          if (that.oldList[0].idClient === nowMsg.idClient) {
            // 相同数据 T出去
            return;
          }
        }
        for (let i = 0; i < that.showArray.length; i++) {
          if (that.showArray[i].aptId === JSON.parse(nowMsg.custom).aptId) {
            that.$set(that.showArray[i], "insert_time", nowMsg.time / 1000);
            that.$set(that.showArray[i], "if_read", 0);
            that.$set(
              that.showArray[i],
              "readNum",
              (that.showArray[i].readNum ? that.showArray[i].readNum : 0) + 1
            );
            that.oldList.push(nowMsg);
            that.$set(that.oldList[0], "idClient", nowMsg.idClient);
            that.showArray.sort((a, b) => {
              return b.insert_time - a.insert_time;
            });
            return;
          }
        }
        console.log(nowMsg, "nowMsg");
        if (that.oldList.length > 0) {
          if (that.oldList[0].idClient === nowMsg.idClient) {
            // 相同数据 T出去
            return;
          } else {
            that.oldList.push(nowMsg);
            that.$set(that.oldList[0], "idClient", nowMsg.idClient);
            that.onGoingToChat(nowMsg);
            return;
          }
          // 该会话不在这里显示的列表
          // 重新查询在进行中的预约,匹配发送消息的对象,把数据补全,才可以点击去聊天页面
        } else {
          that.oldList.push(nowMsg);
          // 该会话不在这里显示的列表
          // 重新查询在进行中的预约,匹配发送消息的对象,把数据补全,才可以点击去聊天页面
          that.onGoingToChat(nowMsg);
        }
        return;
      });
    },
    // 往下滑动加载更多 到顶部刷新
    queryMore() {
      if (this.total == 0) {
        return;
      }
      let up = Math.ceil(this.total / 10);
      if (this.page === up) {
        this.$utils.showToast("text", "没有更多了");
        return;
      }
      this.ongoingList = [];
      this.page++;
      this.ongoingAppointment();
    },
    // 下拉刷新
    onPullDownRefresh() {
      this.triggered = true
      this.page = 1;
      this.showArray = []
      this.ongoingAppointment();
      this.isChooseStatus = false
      this.beingChooseList = []
      this.allCheck = false
    },
    // 医生发来了消息，但是这条问诊消息不在页面显示列表内
    onGoingToChat(nowMsg) {
      let that = this;
      that.$api
        .ongoingAppointment(
          { page: that.page, rows: 100 },
          { showLoading: false }
        )
        .then((res) => {
          return
          let aptId = JSON.parse(nowMsg.custom).aptId;
          for (let i = 0; i < res.data.length; i++) {
            if (aptId === res.data[i].apt_id) {
              let obj = {
                info_type: "0", // 问诊消息
                sonName: res.data[i].doctor_name,
                insert_time: nowMsg.time / 1000,
                if_read: "0", // 如果有未读就为0
                readNum: 1,
                category_str: res.data[i].category_str,
                doctor_identity_desc: res.data[i].doctor_identity_desc,
                dept_name: res.data[i].dept_name,
                aptId: JSON.parse(nowMsg.custom).aptId,
                doctor_netease_id: nowMsg.sessionId.split("-")[1],
                type: 0,
                diagnose_time: res.data[i].diagnose_time,
                diagnose_start_time: res.data[i].diagnose_start_time,
                category: res.data[i].category,
                regular_id: res.data[i].regular_id,
                doctor_name: res.data[i].doctor_name,
                status: res.data[i].status,
                doctorImg: res.data[i].doctor_image_url,
                isChoose: this.allCheck
              };
              if (
                that.$utils.filterTime(obj.insert_time, 2) ==
                that.$utils.filterTime(new Date().getTime() / 1000, 2)
              ) {
                obj.showTime = that.$utils
                  .filterTime(obj.insert_time, 5)
                  .substring(6, 11); // 当天的显示时分
              } else {
                obj.showTime = that.$utils
                  .filterTime(obj.insert_time, 5)
                  .substring(0, 5); // 不是当天的  显示月和日
              }
              that.showArray.unshift(obj);
              that.showArray.sort((a, b) => {
                return b.insert_time - a.insert_time;
              });
              that.showArray = [...that.showArray]
              console.log(that.showArray, "that.onGoingToChat");
            }
          }
        });
        this.triggered = false
    },
    // 全部标记为已读
    readAll() {
      let that = this;
      that.$api.readAll({}, { showLoading: true }).then((res) => {
        for (let i = 0; i < that.showArray.length; i++) {
          that.$set(that.showArray[i], "if_read", "1");
          if (that.showArray[i].info_type == "0") {  // im消息
            that.$set(that.showArray[i], "readNum", 0);
            nim.resetSessionUnread(
              "p2p-" + that.showArray[i].doctor_netease_id
            );
            that.readImInfo(that.showArray[i].doctor_netease_id)
          }
        }
      });
      this.getUnreadStatistic();
    },
    // 标记为已读
    read(i,item) {
      let that = this;
      // 一般消息要调接口,阅读
      if (item.if_read == "1") {
        item.type = 0;
        return;
      }
      if (item.info_type != "0") {
        let param = { information_id: item.information_id }
        if (item.info_type=="4") {
          param = { apt_id: item.aptId }
        }
        that.$api.isReading(param,{ showLoading: true })
          .then((res) => {
            item.if_read = "1";
            item.type = 0;
            this.getUnreadStatistic();
          });
      } else {
        // 问诊消息
        item.if_read = "1";
        item.type = 0;
        item.readNum = 0;
        if(item.chat_type != 1) {
          that.readImInfo(item.doctor_netease_id)
          nim.resetSessionUnread("p2p-" + item.doctor_netease_id); // 会话列表有该id信息才重置
          console.log(this.showArray[i].doctor_netease_id,item.doctor_netease_id)
        }
        this.getUnreadStatistic();
      }
      // this.$router.push(`/pages/center/child/childNews/main?type=${item.type}`)
    },
    // 查询正在进行中的预约
    ongoingAppointment() {
      let that = this;
      that.delayShowData = true // 加载不显示暂无数据
      let arr = [];
      let keyArr = [];
      let sessionArr = [...new Set(that.sessionsList)]
      let obj = {};
      let list = []; // 本次获取的数据
      that.$api.ongoingAppointment({ page: that.page, rows: 10 },{ showLoading: false })
        .then((res) => {
          console.log(res,'正在预约中的数据')
          this.ongoingList = res.data
          this.getUnreadStatistic();
          if (!res.data){
            return null
          }
          list = [...res.data];
          let showTime = ''
          list.forEach((ele,i)=>{
           //  chat_status 0：已删除，1：正常， 2：已撤回
            if(ele.chat_type == 1 && ele.chat_status == '1') {  // 新版留言问诊消息
              showTime = ''
              if (that.$utils.filterTime(ele.send_time, 2) == that.$utils.filterTime(new Date().getTime() / 1000, 2)) {
                showTime = that.$utils
                  .filterTime(ele.send_time?ele.send_time:ele.apt_time, 5)
                  .substring(6, 11); // 当天的显示时分
              } else {
                showTime = that.$utils
                  .filterTime(ele.send_time?ele.send_time:ele.apt_time, 5)
                  .substring(0, 5); // 不是当天的  显示月和日
              }
              obj = {
                  info_type: "4", // 新版留言的问诊消息
                  sonName: list[i].doctor_name,
                  chat_type:1,
                  chat_id: list[i].chat_id,
                  readNum: list[i].unread_count?list[i].unread_count:0,
                  insert_time: list[i].send_time?list[i].send_time:list[i].apt_time,
                  showTime: showTime,
                  if_read: list[i].if_read, // 如果有未读就为0
                  aptId: list[i].apt_id,
                  doctor_netease_id: list[i].doctor_netease_id,
                  category_str: res.data[i].category_str,
                  doctor_identity_desc: res.data[i].doctor_identity_desc,
                  dept_name: res.data[i].dept_name,
                  type: 0,
                  diagnose_time: list[i].diagnose_time,
                  diagnose_start_time: list[i].diagnose_start_time,
                  category: list[i].category,
                  regular_id: list[i].regular_id,
                  doctor_name: list[i].doctor_name,
                  status: list[i].status,
                  doctorImg: list[i].doctor_image_url,
                  time_type: list[i].time_type,
                  information_id: list[i].information_id
                };
                arr.push(obj)
            } else {
              // 云诊间中的 Im 消息 // 或者之前的IM 图文
              sessionArr.forEach((imMsg,imIndex)=>{
                showTime = ''
                if (that.$utils.filterTime(imMsg.lastTime / 1000, 2) == that.$utils.filterTime(new Date().getTime() / 1000, 2)) {
                  showTime = that.$utils
                    .filterTime(imMsg.lastTime / 1000, 5)
                    .substring(6, 11); // 当天的显示时分
                } else {
                  showTime = that.$utils
                    .filterTime(imMsg.lastTime / 1000, 5)
                    .substring(0, 5); // 不是当天的  显示月和日
                }
                if (list[i].apt_id == JSON.parse(imMsg.lastMsg.custom).aptId) {
                    obj = {
                      info_type: "0", // 问诊消息
                      sonName: list[i].doctor_name,
                      chat_type:2,
                      readNum: imMsg.unread,
                      insert_time: parseInt(imMsg.lastTime / 1000),
                      showTime: showTime,
                      if_read: imMsg.unread > 0 ? "0" : "1", // 如果有未读就为0
                      aptId: list[i].apt_id,
                      category_str: res.data[i].category_str,
                      doctor_identity_desc: res.data[i].doctor_identity_desc,
                      dept_name: res.data[i].dept_name,
                      doctor_netease_id: list[i].doctor_netease_id,
                      type: 0,
                      diagnose_time: list[i].diagnose_time,
                      diagnose_start_time: list[i].diagnose_start_time,
                      category: list[i].category,
                      regular_id: list[i].regular_id,
                      doctor_name: list[i].doctor_name,
                      status: list[i].status,
                      doctorImg: list[i].doctor_image_url,
                      time_type: list[i].time_type,
                    };
                  } else {  // 过去的专科订单
                    obj = {
                      info_type: "0", // 问诊消息
                      sonName: list[i].doctor_name,
                      insert_time: list[i].apt_time,
                      showTime: that.$utils.filterTime(list[i].apt_time*1, 5).substring(0, 5),
                      if_read: "1", // 已读
                      chat_type:2,
                      aptId: list[i].apt_id,
                      category_str: res.data[i].category_str,
                      doctor_identity_desc: res.data[i].doctor_identity_desc,
                      dept_name: res.data[i].dept_name,
                      doctor_netease_id: list[i].doctor_netease_id,
                      id: list[i].doctor_netease_id,
                      type: 0,
                      diagnose_time: list[i].diagnose_time,
                      diagnose_start_time: list[i].diagnose_start_time,
                      category: list[i].category,
                      regular_id: list[i].regular_id,
                      doctor_name: list[i].doctor_name,
                      status: list[i].status,
                      doctorImg: list[i].doctor_image_url,
                      time_type: list[i].time_type,
                    };
                  }
                  arr.push(obj);
              })
            }
          })
          //去重
          // that.showArray = [...new Set(arr)];
          console.log(arr,'arrrrr')
          return {thatList:arr, total:res.total}
        })
        .then(info => {
          console.log(info,'传参')
          let arr1 = [];
          // 一般消息
          that.$api.getInformationList({ type: that.type, page: that.page, rows: 10 },{ showLoading: true })
            .then((res) => {
              that.total = res.total + info.total
              arr1 = res.data
              if (arr1.length > 0) {
                for (let i = 0; i < arr1.length; i++) {
                  arr1[i].isChoose = this.allCheck  // 选择状态
                  if (
                    that.$utils.filterTime(arr1[i].insert_time, 2) ==
                    that.$utils.filterTime(new Date().getTime() / 1000, 2)
                  ) {
                    arr1[i].showTime = that.$utils
                      .filterTime(arr1[i].insert_time, 5)
                      .substring(6, 11); // 当天的显示时分
                  } else {
                    arr1[i].showTime = that.$utils
                      .filterTime(arr1[i].insert_time, 5)
                      .substring(0, 5); // 不是当天的  显示月和日
                  }
                  arr1[i].type = 0;
                }
              }
              //  合并两种类型 消息处理
              arr1.push(...info.thatList)
              //去重
              arr1 = [...new Set(arr1.concat(that.showArray))];
              // 排序
              arr1.sort((a, b) => {
                return b.insert_time*1 - a.insert_time*1;
              });
              that.showArray = [...new Set(arr1)]
              that.delayShowData = false
              wx.stopPullDownRefresh();
            });
            that.triggered = false
        });
    },
    // 去子页面
    goList(item) {
      let type = "";
      if (item.value === 0) {
        type = "0";
      } else if (item.value === 2) {
        type = "2";
      } else if (item.value === 3) {
        type = "3";
      } else if (item.value === 1) {
        this.$utils.showToast("text", "暂未开通");
        return;
      }
      this.$router.push(`/pages/center/child/childNews/main?type=${type}`);
    },
    // 滑动开始
    touchStart(e, index) {
      if(this.isChooseStatus) return
      // 获取移动距离，可以通过打印出e，然后分析e的值得出
      this.startX = e.mp.changedTouches[0].clientX;
      for (let i = 0; i < this.showArray.length; i++) {
        if (i === index) {
        } else {
          this.$set(this.showArray[i], "type", 0);
        }
      }
    },
    // 滑动结束
    touchEnd(e, index) {
      if(this.isChooseStatus) return
      // 获取移动距离
      this.endX = e.mp.changedTouches[0].clientX;
      if (this.startX - this.endX > 10) {
        for (let i = 0; i < this.showArray.length; i++) {
          this.$set(this.showArray[index], "type", 0);
        }
        this.$set(this.showArray[index], "type", 1);
      } else if (this.startX - this.endX < -10) {
        for (let i = 0; i < this.showArray.length; i++) {
          this.$set(this.showArray[i], "type", 0);
        }
      }
    },
    // 标记im消息已读
    readImInfo(id) {
      let that = this
      for (let i = 0; i < that.sessionsList.length; i++) {
          if (that.sessionsList[i].id == "p2p-" + id) {
            that.sessionsList[i].unread = 0
            that.$store.commit(that.$types.SESSIONS_LIST, that.sessionsList);
          }
        }
    },
    // 点击恢复原状
    recover(index, item) {
      let that = this;
      if (that.isChooseStatus) {
        that.chooseMsg(index)
        return
      }
      that.$set(that.showArray[index], "type", 0);
      if (item.info_type == "0") {
        let obj = {
          apt_diagnose_time: item.diagnose_start_time,
          diagnose_time: item.diagnose_time,
          apt_id: item.aptId,
          category: item.category,
          regular_id: item.regular_id,
          doctor_name: item.doctor_name,
          netease_id: item.doctor_netease_id,
          sessionId: "p2p-" + item.doctor_netease_id,
          status: item.status,
          doctorImg: item.doctorImg,
          time_type: item.time_type
        };
        that.$store.commit(that.$types.TALK_INFO, obj); // 保存talkinfo
        nim.resetSessionUnread("p2p-" + item.doctor_netease_id); // 会话列表有该id信息才重置
        // 清除sessionList 里面对应id的已读数据
        that.readImInfo(item.doctor_netease_id);
        console.log(that.sessionsList,'sessionsList',item.doctor_netease_id,item)
        // that.$store.commit(that.$types.SESSIONS_LIST, that.sessionsList);
        // 音频
        item.if_read = "1";
        console.log(item)
        if (item.category === "4" || item.category === "5") {
          if (item.chat_type=='1') {
            that.$router.push( `/pages/chat/child/leaveMsg/main?hadAudio=true&apt_id=${item.aptId}&category=${item.category}`);
          } else {
            that.$router.push(`/pages/chat/child/graphicChat/main?hadAudio=true`);
          }
        } else {
          // 图文
          if (item.chat_type=='1') {
            that.$router.push(`/pages/chat/child/leaveMsg/main?apt_id=${item.aptId}`);
          } else { // 专科 专家
            that.$router.push(`/pages/chat/child/graphicChat/main?canSend=1`);
          }
        }
      } else {
        if (item.info_type == "4") {
          let obj = {
            apt_diagnose_time: item.diagnose_start_time,
            diagnose_time: item.diagnose_time,
            apt_id: item.aptId,
            category: item.category,
            regular_id: item.regular_id,
            doctor_name: item.doctor_name,
            netease_id: item.doctor_netease_id,
            sessionId: "p2p-" + item.doctor_netease_id,
            status: item.status,
            doctorImg: item.doctorImg,
            time_type: item.time_type
          };
          that.$store.commit(that.$types.TALK_INFO, obj); // 保存talkinfo
          if (item.category === "4" || item.category === "5") {
              if (item.chat_type=='1') {
                that.$router.push( `/pages/chat/child/leaveMsg/main?hadAudio=true&apt_id=${item.aptId}&category=${item.category}`);
              } else {
                that.$router.push(`/pages/chat/child/graphicChat/main?hadAudio=true`);
              }
            } else {
              // 图文
              if (item.chat_type=='1') {
                that.$router.push(`/pages/chat/child/leaveMsg/main?apt_id=${item.aptId}`);
              } else {
                that.$router.push(`/pages/chat/child/graphicChat/main`);
              }
            }
          if (item.information_id){  // 留言聊天标记已读
            that.$api.isReading({ information_id: item.information_id },{ showLoading: true }).then(res=>{})
          }
          return
        }
        if (
          item.to_link &&
          (item.to_link.type == "follow_serveys" ||
            item.to_link.type == "return_serveys" ||
            item.to_link.type == "exclusive_survey")
        ) {
          that.$utils.showToast("text", "请前往武大云医APP查看和填写");
          return;
        }
        that.$api
          .isReading(
            { information_id: item.information_id },
            { showLoading: true }
          )
          .then((res) => {
            item.if_read = "1";
            item.type = 0;
            if (item.info_type == "3") { // 系统消息
              if (item.to_link && item.to_link.type == "appointment") {
                let obj = {
                  apt_id: item.to_link.id,
                };
                that.$store.commit(that.$types.TALK_INFO, obj);
                that.$router.push(
                  `/pages/center/child/appointmentDetails/main?aptId=${item.aptId}`
                );
              } else if (item.to_link && item.to_link.type == "follow_serveys_detail") {
                that.$router.push(
                  `/pages/subPage/register/webView/main?id=${item.to_link.id}`
                );
              } else if (item.to_link && item.to_link.type === 'offlineappointment') {
                this.$router.push("/pages/center/child/appointmentRecord/main?isOffline=true")
              }
                else {
                that.$router.push(
                  `/pages/center/child/remindDetails/main?id=${item.information_id}`
                );
              }
            } else if (item.info_type == "1") {
              this.$utils.showToast("text", "暂未开通");
            } else if (item.info_type == "2") {
              that.$router.push(
                `/pages/center/child/remindDetails/main?id=${item.information_id}`
              );
            }
          });
      }
    },
    // 单个删除
    delect(index, item) {
      let that = this;
      // 一般消息要调接口
      if (item.info_type != "0") {
        let arr = [], newChatList = [], param = {}
        newChatList.push(item.chat_id)
        arr.push(item.information_id);
        if (item.info_type == "4") {
          param = {
            chat_info_id: newChatList
          }
        } else {
          param = {
            info_list: arr
          }
        }
        that.$api
          .deleteInfo(param, { showLoading: true })
          .then((res) => {
            that.showArray.splice(index, 1);
            $Toast({
              content: '删除成功',
              type: 'success'
            })
            this.getUnreadStatistic();
          });
      } else {
        // 问诊消息
        nim.resetSessionUnread("p2p-" + item.doctor_netease_id); // 会话列表有该id信息才重置
        // 删除服务器会话
        nim.deleteSession({
          scene: "p2p",
          to: item.doctor_netease_id,
          done: that.deleteSessionDone,
        });
        $Toast({
          content: '删除成功',
          type: 'success'
        })
        this.getUnreadStatistic();
      }
    },
    deleteSessionDone(error, obj) {
      let that = this;
      if (error) {
        console.log("删除失败");
        nim.reconnection();
      } else {
        // 找出showArray里面所有一样的netease_id的数据集合 一起删掉
        let indexList = [];
        for (let i = 0; i < that.showArray.length; i++) {
          if (obj[0].to == that.showArray[i].doctor_netease_id) {
            indexList.push(that.showArray[i].aptId);
          }
        }
        for (let i = 0; i < indexList.length; i++) {
          for (let j = 0; j < that.showArray.length; j++) {
            if (indexList[i] == that.showArray[j].aptId) {
              that.showArray.splice(j, 1);
            }
          }
        }
        // 清除sessionList 里面对应id的数据
        for (let i = 0; i < that.sessionsList.length; i++) {
          if (that.sessionsList[i].id == "p2p-" + obj[0].to) {
            that.sessionsList.splice(i, 1);
            that.$store.commit(that.$types.SESSIONS_LIST, that.sessionsList);
            return;
          }
        }
      }
    },
    wantChooseMsg () {
      this.isChooseStatus = !this.isChooseStatus;
      this.beingChooseList = []
      this.allCheck = false
      this.showArray.forEach((ele,i)=>{
        this.$set(this.showArray[i],'isChoose',this.allCheck)
      })
    },
    // 设置导航栏的高度等信息
    getNavInfo () {
      let menuButtonObject = wx.getMenuButtonBoundingClientRect();
      // console.log(menuButtonObject, '胶囊属性值')
      this.navBtnInfo = menuButtonObject
    },
    goBack :function () {
      let pages = getCurrentPages();
      if (pages.length===1) {
        this.$router.replace('/pages/index/main')
        return
      }
      this.$router.go(-1)
    },
    // 选择要删除的信息
    chooseMsg (index) {
      this.$set(this.showArray[index], 'isChoose', !this.showArray[index].isChoose)
      if (this.showArray[index].isChoose) {
        this.beingChooseList.push(this.showArray[index].information_id)
      } else {
        let i = this.beingChooseList.findIndex((current)=>{
          return this.showArray[index].information_id === current
        })
        if (i !== -1) {
          this.beingChooseList.splice(i,1)
        }
      }
    },
    // 全选
    checkAllMsg () {
      this.allCheck = !this.allCheck;
      this.showArray.forEach((ele,i)=>{
        this.$set(this.showArray[i],'isChoose',this.allCheck)
        this.beingChooseList.push(ele.information_id)
      })
      if(!this.allCheck) {
        this.beingChooseList = []
      }
    },
    // 批量删除
    batchDelete () {
      this.beingChooseList = [...new Set(this.beingChooseList)]  // 去重
      console.log(this.beingChooseList, '要删除的数组')
      if (this.beingChooseList.length < 1) {
        $Toast({
          content: '请选择要删除的消息',
          type: 'warning'
        })
        return
      }
      let list = this.beingChooseList.concat([])
      let nowIndex = 0 // 同步beingChangeList 数组长度的变化
      list.forEach((ele,index)=>{  // 处理问诊信息的提醒
        let i = this.showArray.findIndex((current)=>{
            return ele === current.information_id
        })
        if (this.showArray[i] && this.showArray[i].info_type == "0"){
          console.log(this.showArray[i])
          // 问诊消息
          nim.resetSessionUnread("p2p-" + this.showArray[i].doctor_netease_id); // 会话列表有该id信息才重置
          // 删除服务器会话
          nim.deleteSession({
            scene: "p2p",
            to: this.showArray[i].doctor_netease_id,
            done: this.deleteSessionDone,
          });
          this.beingChooseList.splice(nowIndex, 1)
        } else {
          this.showArray.splice(i, 1);
          nowIndex ++ // 没有删除的才让 nowindex自增
        }
      })
      console.log(this.beingChooseList,'在这呢',list)
      let param = {
        info_list: this.beingChooseList
      }
      if (this.allCheck) {
        param = {
          check_all: '1'
        }
      }
      this.$api.deleteInfo(param, { showLoading: false }).then((res) => {
        $Toast({
          content: '删除成功',
          type: 'success'
        })
        // setTimeout(() => {
        //   this.showArray = []
        //   // this.ongoingAppointment();
        // }, 1000);
      });
      this.beingChooseList = []
      this.isChooseStatus = false
      this.allCheck = false
      this.showArray.forEach((ele,i)=>{
        this.$set(this.showArray[i],'isChoose',this.allCheck)
      })
      this.getUnreadStatistic();
      setTimeout(() => {
        this.showArray = []
        this.page = 1;
        this.ongoingAppointment();
      }, 300);
    },
    judgeUnread(list,id) {
      let judge = false;
      list.forEach(ele=>{
        if(ele.apt_id === id) {
          judge = true
          return
        }
      })
      return judge
    },
    // 消息红点显示数字
    getUnreadStatistic() {
      console.log(this.sessionsList,)
      this.unreadStatic.chat_info = 0
      this.$api.commentUnreadStatistic({},({'showLoading':false})).then(res=>{
        this.unreadStatic = res.data
        let num = 0
        for (let i = 0; i < this.sessionsList.length; i++) {
          // 需要判断 im的消息是否为当前正在进行中的订单
          if (this.sessionsList[i].unread > 0 && this.judgeUnread(this.ongoingList,JSON.parse(this.sessionsList[i].lastMsg.custom).aptId)) {
            num+=this.sessionsList[i].unread*1
          }
        }
        this.unreadStatic.chat_info += num
      })
    }
  },
};
</script>
<style scoped lang="less">
.subPage {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.fillBottom {
  height: 10rpx;
  background-color: #3f4ade;
}
.top {
  height: 236rpx;
  position: relative;
  .backgr {
    height: 170rpx;
    width: 100%;
    background: linear-gradient(90deg, #557DF5 0%, #3F4ADE 100%);
  }
  .init {
    position: absolute;
    left: 35rpx;
    top: 0;
    width: 680rpx;
    height: 236rpx;
    box-shadow: 0px 2rpx 9rpx 0rpx rgba(0, 0, 0, 0.15);
    border-radius: 26rpx;
    background: #ffffff;
    display: flex;
    .item {
      position: relative;
      flex: 1;
      text-align: center;
      color: #666666;
      .unReadPoint {
        position: absolute;
        height: 36rpx;
        min-width: 36rpx;
        background: linear-gradient(315deg, #ff3332 0%, #ff6f91 100%);
        top: 26rpx;
        right: 22rpx;
        border-radius: 18rpx;
        color: #fff;
        font-size: 22rpx;
        line-height: 36rpx;
        padding: 0 4rpx;
        box-sizing: border-box;
      }
    }
    img {
      width: 118rpx;
      height: 118rpx;
      display: inline-block;
      margin: 31rpx 0 7rpx 0;
    }
  }
}
.msglist {
  flex: 1;
  overflow-y: auto !important;
  .noneimg {
    width: 550rpx;
    height: 360rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -275rpx;
    margin-top: -180rpx;
  }
  .hadMsg {
    text-align: center;
    margin: 27rpx 0 0 0;
    span {
      display: inline-block;
      padding: 5rpx 16rpx;
      background: #f3f3f3;
      border-radius: 25px;
      color: #4b7aea;
      font-size: 28rpx;
    }
  }
}
.infoAll {
  width: 100%;
  overflow: hidden;
  ul {
    width: 100%;
    /* // overflow-x: scroll; */
    li {
      -webkit-transition: all 0.2s;
      transition: all 0.2s;
      width: 1150rpx;
      height: 200rpx;
      border-bottom: 1rpx solid #e9e9e9;
      display: flex;
      align-items: center;
      .imgInfo {
        width: 118rpx;
        height: 118rpx;
        border-radius: 50%;
        margin-left: 20rpx;
        img {
          width: 118rpx;
          height: 118rpx;
          overflow: hidden;
        }
      }
      .imgChooseMargin {
        margin-left: 0rpx;
      }
      .chooseImg {
        height: 100%;
        width: 8%;
        position: relative;
        img {
          position: absolute;
          top: 50%;
          left: 36rpx;
          transform:translateY(-50%);
          height: 30rpx;
          width: 30rpx;
        }
      }
      .centerInfo {
        width: 55%;
        height: 200rpx;
        margin-left: 18rpx;
        margin-right: 120rpx;
        .name {
          margin-top: 38rpx;
          .radius {
            display: inline-block;
            height: 15rpx !important;
            width: 15rpx !important;
            margin-left: 10rpx;
            border-radius: 100%;
            background: red;
          }
          span {
            color: #7c8489;
            height: 50rpx;
            font-size: 34rpx;
            font-weight: 400;
            color: rgba(51, 51, 51, 1);
            line-height: 50rpx;
            display: flex;
            align-items: center;
          }
          .radiusNum {
            display: inline-block;
            font-size: 20rpx !important;
            background: red;
            color: #fff;
            line-height: 0;
            height: 30rpx;
            width: 30rpx;
            text-align: center;
            line-height: 30rpx;
            border-radius: 100%;
            margin-left: 10rpx;
          }
          .time {
            height: 44rpx;
            font-size: 28rpx;
            font-weight: 400;
            color: rgba(153, 153, 153, 1);
            line-height: 44rpx;
          }
        }
        .sonName {
          span {
            color: #999;
            height: 80rpx;
            font-size: 28rpx;
            font-weight: 400;
            line-height: 40rpx;
          }
          .info {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
        }
      }
      .chooseWidth {
        width: 48%;
      }
      .top {
        width: 15%;
        height: 200rpx;
        line-height: 200rpx;
        background-color: #c4c7cd;
        color: #fff;
        font-size: 34rpx;
        text-align: center;
      }
      .delect {
        width: 15%;
        height: 200rpx;
        line-height: 200rpx;
        background-color: #ff3b32;
        color: #fff;
        font-size: 34rpx;
        text-align: center;
      }
    }
  }
}
li[data-type="0"] {
  transform: translate3d(0, 0, 0);
}
li[data-type="1"] {
  transform: translate3d(-400rpx, 0, 0);
}
.bottomChooseBox {
  position: fixed;
  bottom: 0;
  width:750rpx;
  height:90rpx;
  background:rgba(255,255,255,1);
  box-shadow:0px -1px 7px 0px rgba(0,0,0,0.14);
  span {
    margin: 0 31rpx;
    display: inline-block;
    height: 100%;
    line-height: 90rpx;
    img {
      position: absolute;
      top: 50%;
      // left: 36rpx;
      transform:translateY(-50%);
      height: 30rpx;
      width: 30rpx;
    }
  }
  .leftCheckBox{
    position: relative;
  }
  .redFont {
    color: red;
  }
  .deleteBtn {
    color: gray;
  }
  .canDelete {
    color:#4B7AEA;
  }
}
.ifIphonex {
  padding-bottom: 20rpx;
}
</style>
